package cn.gson.boot.model.service;

import cn.gson.boot.model.dao.*;
import cn.gson.boot.model.mapper.*;
import cn.gson.boot.model.pojos.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Timestamp;
import java.util.*;

@Service
@Transactional(rollbackFor = Exception.class)
public class HeTongService {
    @Autowired
    HeTongDao heTongDao;//合同
    @Autowired
    HeTongXiangQingDao heTongXiangQingDao;//合同详情
    @Autowired
    HeTongXiangQingMapper heTongXiangQingMapper;
    @Autowired
    HeTongMapper heTongMapper;
    @Autowired
    HTDDKeHuDao htddKeHuDao;//客户
    @Autowired
    HTBaoJiaDanDao htBaoJiaDanDao;//报价单
    @Autowired
    HTDDUserDao htddUserDao;//员工
    @Autowired
    HTBaoJiaDanMingXiDao htBaoJiaDanMingXiDao;//报价明细

    @Autowired
    DinDanDao dinDanDao;//订单
    @Autowired
    DingDanMapper dingDanMapper;
    @Autowired
    DinDanXiangQingDao dinDanXiangQingDao;//订单详情
    @Autowired
    DingDanXiangQingMapper dingDanXiangQingMapper;
    @Autowired
    QuotationDao quotationDao;
    @Autowired
    SalesDao salesDao;
    //审核
    @Autowired
    ShenHeDao shenHeDao;

    @Autowired
    MainPageMapper mainPageMapper;

    @Autowired
    JiaoFuJiHuaMapper jiaoFuJiHuaMapper;

    //查询客户
    public List<Kehu> selectKehu(){
        return mainPageMapper.selectKehu();
    }

    //根据客户id来查询客户所对应的报价单
    public List<Quotation> selectBaoJiaDidanByKeHU(Integer khid){
        return heTongMapper.selectBojiaDanByKeHu(khid);
    }
    //根据客户名称来查询客户id
    public Integer selectKhIdBykhName(String khName) {
        System.err.println("heTongMapperheTongMapper.selectkhid(khName).getkId():"+heTongMapper.selectkhid(khName).getkId());
        return heTongMapper.selectkhid(khName).getkId();
    }

    //根据客户名称来查询客户
    public Kehu selectKhIdBykhNameDuixiang(String khName) {
        return heTongMapper.selectkhid(khName);
    }

    //根据员工名字找员工
    public User selectEmpIdByEmpName(String empName) {
        return htddUserDao.selectEmpid(empName);
    }

    //查询员工
    public List<User> selectUser(){
        return htddUserDao.selectUser();
    }

    //根据报价单id查询报价明细
    public List<Quotationdetails> selectBaoJiaMingXi(Integer baojiaId){
        return heTongMapper.selectBaoJiaMingXi(baojiaId);
    }

    //新增合同和合同详情
    public void addHetongAndXiangQing(Hetong hetong) {
        hetong.setHtYs(1);
        Hetongxiangqing hx = null;
        System.err.println("hetong.getHtSh():"+hetong.getHtSh());
        if(hetong.getHtId()!=0){
           heTongXiangQingDao.deleteHeTongXiangQing(hetong.getHtId());
           hetong.setHtSh(hetong.getHtSh());
           hetong.setHtSh(hetong.getHtSh());
           heTongDao.save(hetong);
        }else if(hetong.getHtId() == 0){
            hetong.setHtSh("待审核");
            Hetong savev = heTongDao.save(hetong);
            Shenhe shenhe = new Shenhe();
            shenhe.setShTabid(savev.getHtId());
            shenhe.setShShouming("合同" );
            shenhe.setChuangJiantime(savev.getHtQianyuetime());
            shenhe.setShZhuangtai("待审核");
            shenhe.setEmp(null);
            shenhe.setShenqingPeople(savev.getEmp().getEmpName());
            System.err.println("有包：" + shenhe.getShZhuangtai());
            shenHeDao.save(shenhe);
        }
        System.out.println("============================");
        System.err.println("长度长度："+hetong.baoJiaMingXiList.size());
        System.out.println("============================");
        for (int i=0;i<hetong.baoJiaMingXiList.size();i++){
            hx = new Hetongxiangqing();
            hx.setHetongByHtId(hetong);
            hx.setHtcpMun(hetong.baoJiaMingXiList.get(i).getQuotationdNum());
            hx.setHtcpPrice(hetong.baoJiaMingXiList.get(i).getQuotationdPrice());
            hx.setProductt(hetong.baoJiaMingXiList.get(i).getProductt());
            hx.setHtcpXiaoji(hetong.baoJiaMingXiList.get(i).getQuotationdMoney());
            heTongXiangQingDao.save(hx);
        }


        /*Quotation quotation = quotationDao.findById(hetong.getQuotation().getQuotationId()).get();
        Sales sales = salesDao.findById(quotation.getSales().getSalesId()).get();
        Stage stage = new Stage();
        stage.setStageId(5);
        sales.setStage(stage);
        sales.setSalesPossibility("100%");
        salesDao.save(sales);*/
    }

    //查看所有合同
    public List<Hetong> selectAllHeTong(String ddHao,String khName,String time,String htSh,String empName){
        return heTongMapper.selectAllHeTong(ddHao,khName,time,htSh,empName);
    }

    //查看合同详情根据合同id
    public List<Hetongxiangqing> ckHeTongXiangQing(Integer htid) {

        return heTongXiangQingMapper.ckHeTongXiangQing(htid);
    }


    //移除合同
    public String yichuHeTong(Integer htid) {
        String fh = null;
        Hetong hetong = heTongMapper.selectHeTongByHtId(htid).get(0);
        //如果合同的审核状态为待审核，就可以进行物理删除
        //并且在审核表里面也要删除这条合同的审核
        if(hetong.getHtSh().equals("待审核")){
            shenHeDao.delectShenHe(htid,"合同");
            heTongXiangQingDao.deleteHeTongXiangQing(htid);
            heTongDao.delectHeTong(htid);
            fh = "删除成功";
        }else{
            //逻辑删除
            //根据合同id查找订单集合
            List<Dingdan> ddList = dingDanMapper.ckDingDanListByhtId(htid);
            //如果合同在订单里面引用了，就不能逻辑移除
            if(ddList.size()==0){
                heTongDao.yichuHeTong(htid);
                fh = "移除成功";
            }else {
                fh = "移除失败，此合同已被引用";
            }
        }
        return fh;
    }



    //订单==========================================================================

    //新建订单，查看所有的合同状态是执行中的合同
    public List<Hetong> ddCkHt() {
        return heTongMapper.ddCkHt();
    }

    //根据合同号查合同详情
    public List<Hetongxiangqing> selectDDHeTongXaingQing(Integer htId) {
        return heTongMapper.selectDDHeTongXaingQing(htId);
    }
    //根据合同id查看订单详情<四个表：合同，订单，订单详情，产品>(mybatis查询)
    public List<Dingdanxiangqing> selectDDDingDanXaingQing(Integer htId) {
        return dingDanXiangQingMapper.selectDDDingDanXaingQing(htId);
    }


    @Autowired
    ContactsDao contactsDao;
    //新建订单
    public void addDinDan(Dingdan dingdan) {
        dingdan.setDdYs(1);
        Dingdanxiangqing dx = null;
        if(dingdan.getDdId()!=0){
            dinDanXiangQingDao.deleteDinDanXiangQing(dingdan.getDdId());
            dinDanDao.save(dingdan);
        }else if(dingdan.getDdId() == 0){
            String[] arr = dingdan.getDdShouhuoren().split("/");
            dingdan.setDdShouhuoren(arr[0]);
            Dingdan savev =  dinDanDao.save(dingdan);
            //把订单的审核注释了，换成了交付计划的审核
           /* Shenhe shenhe = new Shenhe();
            shenhe.setShTabid(savev.getDdId());
            shenhe.setShShouming("订单" );
            shenhe.setChuangJiantime(savev.getDdTime());
            shenhe.setShZhuangtai("待审核");
            shenhe.setEmp(null);
            shenhe.setShenqingPeople(savev.getDdSyz());
            System.err.println("有包：" + shenhe.getShZhuangtai());
            shenHeDao.save(shenhe);*/
           System.out.println("ADDDD新建联系人："+arr[1]);
           if(arr[1].equals("ADD")){
                Contacts contacts = new Contacts(arr[0], Long.valueOf(dingdan.getDdPhone()), dingdan.getProvince(),
                        dingdan.getCity(), dingdan.getArea(), dingdan.getDdAddress(),dingdan.getkH(),
                        new Timestamp(new Date().getTime()),1);
                contactsDao.save(contacts);
           }
        }
        System.out.println("============================");
        System.err.println("长度长度："+dingdan.ddheTongList.size());
        System.out.println("============================");
        for (int i=0;i<dingdan.ddheTongList.size();i++){
          //  System.out.println("产品名称id："+dingdan.ddheTongList.get(i).getProduct().getProductName());
            dx = new Dingdanxiangqing();

            dx.setProductt(dingdan.ddheTongList.get(i).getProductt());
            dx.setDdcpNum(dingdan.ddheTongList.get(i).getHtcpMun());
            dx.setDdcpPrice(dingdan.ddheTongList.get(i).getHtcpPrice());
            dx.setDingdanByDdId(dingdan);
            dx.setDdxqXiaoji(dingdan.ddheTongList.get(i).getHtcpXiaoji());

            dinDanXiangQingDao.save(dx);
        }
    }

    //查看所有订单
    public List<Dingdan> selectAllDingDan(Dingdan dingdan){
        return dingDanMapper.selectAllDingDan(dingdan);
    }
    //查看所有订单
    public List<Dingdan> selectAllDingDan2(String ddHao,String khName,String time,String ddZt,String empName){
        return dingDanMapper.selectAllDingDan2(ddHao,khName,time,ddZt,empName);
    }

    //根据订单id查看订单详情
    public List<Dingdanxiangqing> ckDingDanXiangQing(Integer ddid) {
        return dingDanXiangQingMapper.ckDingDanXiangQing(ddid);
    }

    //移除订单
    public String yichuDingDan(Integer ddid) {
        String fh = null;
        //根据订单id查看此订单交付计划
        List<Jiaofujihua> jfjh = jiaoFuJiHuaMapper.ckJiaofujihuaByDdId(ddid);
        //根据订单id查看此订单交付计划
        List<Jiaofujihua> jfjhfj = jiaoFuJiHuaMapper.ckJiaofujihuaFouJueByDdId(ddid);

        Dingdan dd = dingDanMapper.selectDDByDDid(ddid).get(0);
        //如果是换货单生成的订单，就不能删除
        if(dd.getDdIshh()==2){
            fh = "此订单是根据换货单生成的，不能移除";
        }else {
            //判断一下订单是否已经生成了交付计划，
            if(jfjh.size()==0){
                //如果没有就可以进行物理删除
                dinDanXiangQingDao.deleteDinDanXiangQing(ddid);
                dinDanDao.deleteDingDan(ddid);
                fh = "删除成功";
            }else {
                if(jfjhfj.size() == jfjh.size()){
                    dinDanDao.yichuDingDan(ddid);
                    fh = "移除成功";
                }else {
                    fh = "移除失败，此合同已经生成了交付计划";
                }
            }
        }
        return fh;
    }

    //根据合同id查看合同
    public List<Hetong> selectHeTongByHtId(Integer htId){
        return heTongMapper.selectHeTongByHtId(htId);
    }

    //交付计划（查看所有订单）
    public List<Dingdan> jfjhSelectAllDingDan(){
        return dingDanMapper.jfjhSelectAllDingDan();
    }

    //<!--发货：查看所有订单-->
    public List<Dingdan> fahuoSelectAllDingDan(){
        return dingDanMapper.fahuoSelectAllDingDan();
    }
    //<!--发货：查看所有订单 换货-->
    public List<Dingdan> fahuoSelectAllDingDan2(){
        return dingDanMapper.fahuoSelectAllDingDan2();
    }
    //<!--退/换货：查看所有订单-->
    public List<Dingdan> tuiHuanHuoSelectAllDingDan(){
        return dingDanMapper.tuiHuanHuoSelectAllDingDan();
    }

    //根据选择的订单获取订单详情
    public List<Dingdanxiangqing> selectDingDanByDdId(Integer ddid) {
        return dingDanXiangQingMapper.ckDingDanXiangQing(ddid);
    }

    //根据订单id获取订单
    public List<Dingdan> selectDDByDDid(Integer ddId) {
        return dingDanMapper.selectDDByDDid(ddId);
    }

    //根据合同查到此合同包含的订单
    public List<Dingdan> selectheBaoHangDeDingDan(Integer htId){
        return dingDanMapper.selectheBaoHangDeDingDan(htId);
    }

    /*重复购买订单*/
    @Autowired
    CFGMDingDanDao cfgmDingDanDao;
    @Autowired
    CFGMDinDanXiangQingDao cfgmDinDanXiangQingDao;
    //新建重复购买订单
    public void addCFGMdingdan(CFGMDingdan cfgmDingdan) {
        cfgmDingdan.setDdYs(1);
        cfgmDingDanDao.save(cfgmDingdan);
        CFGMDingdanxiangqing dx = null;
     /*   if(cfgmDingdan.getDdId()!=0){
            dinDanXiangQingDao.deleteDinDanXiangQing(cfgmDingdan.getDdId());
        }*/
     System.err.println("ads:"+cfgmDingdan.ddXiangQingList.size());
        for (int i=0;i<cfgmDingdan.ddXiangQingList.size();i++){
            dx = new CFGMDingdanxiangqing();
            dx.setProductt(cfgmDingdan.ddXiangQingList.get(i).getProductt());
            dx.setDdcpNum(cfgmDingdan.ddXiangQingList.get(i).getDdcpNum());
            dx.setDdcpPrice(cfgmDingdan.ddXiangQingList.get(i).getDdcpPrice());
            dx.setDingdanByDdId(cfgmDingdan);
            dx.setDdxqXiaoji(cfgmDingdan.ddXiangQingList.get(i).getDdxqXiaoji());

           cfgmDinDanXiangQingDao.save(dx);
        }

    }

    //查看所有重复购买订单
    public List<Dingdan> ckcfgmDingDan(String ddHao,String khName,String time) {
        return dingDanMapper.ckcfgmDingDan(ddHao,khName,time);
    }


    //=====================维修工单
    //根据选择的客户查询客户所有的订单
    public List<Dingdan> ckdingdan(Integer kId) {
        return dingDanMapper.ckdingdan(kId);
    }


    //回款  根据选择的客户查询客户所有的订单
    public List<Dingdan> huiKuanCkdingdan(Integer kId){
        return dingDanMapper.huiKuanCkdingdan(kId);
    }

    //根据选择的订单查到此订单详情表里面的产品
    public List<Productt> ckDingDanChanPin(Integer ddId) {
        return dingDanXiangQingMapper.ckDingDanChanPin(ddId);
    }

    //根据产品查询订单详情的信息
    public Dingdanxiangqing ckDingDanChanXiangQinByChanPin(Integer producttId,Integer ddId) {
        return dingDanXiangQingMapper.ckDingDanChanXiangQinByChanPin(producttId,ddId);
    }

    //根据订单id查到订单信息
    public Dingdan ckDingDanByddId(Integer ddId) {
        return dingDanMapper.ckDingDanByddId(ddId);
    }



    /*统计图*/

    //合同thtj
    public List<Integer> hetongtj() {
        List<Integer> tj = new ArrayList<>();
        tj.add(heTongDao.yshHt());//已审核
        tj.add(heTongDao.dshHt());//待审核的合同
        tj.add(heTongDao.wcHt());//完成的合同
        tj.add(heTongDao.zxzHt());//执行中的合同
        tj.add(heTongDao.ywzzHt()); //意外终止的合同
        return tj;
    }
    //合同状态
    public Map<String,Object> htZhuanTai(){
        Map<String,Object> map = new HashMap<>();
        List<Integer> sj = new ArrayList<>();
        sj.add(heTongDao.wksHt());//未开始
        sj.add(heTongDao.wcHt());//完成的合同
        sj.add(heTongDao.zxzHt());//执行中的合同
        sj.add(heTongDao.ywzzHt()); //意外终止的合同
        List<String> mz = new ArrayList<>();
        mz.add("未开始");
        mz.add("完成");
        mz.add("执行中");
        mz.add("意外终止");
        map.put("sj",sj);
        map.put("mz",mz);
        return map;
    }
    //审核状态
    public Map<String,Object> htSh(){
        Map<String,Object> map = new HashMap<>();
        List<Integer> sj = new ArrayList<>();
        sj.add(heTongDao.yshHt());//同意的合同
        sj.add(heTongDao.dshHt());//待审核的合同
        sj.add(heTongDao.shzHt()); //审核中的合同
        sj.add(heTongDao.fjHt()); //否决的合同
        List<String> mz = new ArrayList<>();
        mz.add("同意");
        mz.add("待审核");
        mz.add("审核中");
        mz.add("否决");
        map.put("sj",sj);
        map.put("mz",mz);
        return map;
    }
    //用户
    public Map<String,Object> htYh(){
        Map<String,Object> map = new HashMap<>();
        List<Integer> sj = new ArrayList<>();
        List<String> mz = new ArrayList<>();
        List<Kehu> kh = heTongMapper.tjKh();
        for (int i=0;i<kh.size();i++){
            sj.add(heTongDao.khHt(kh.get(i).getkId()));
            mz.add(kh.get(i).getkName());
        }
        map.put("sj",sj);
        map.put("mz",mz);
        return map;
    }
    //报价单
    public Map<String,Object> htBjd(){
        Map<String,Object> map = new HashMap<>();
        List<Integer> sj = new ArrayList<>();
        List<String> mz = new ArrayList<>();
        List<Quotation> bjd = heTongMapper.tjBjd();
        for (int i=0;i<bjd.size();i++){
            sj.add(heTongDao.bjdHt(bjd.get(i).getQuotationId()));
            mz.add(bjd.get(i).getQuotationName());
        }
        map.put("sj",sj);
        map.put("mz",mz);
        return map;
    }
    //所有者
    public Map<String,Object> htSyz(){
        Map<String,Object> map = new HashMap<>();
        List<Integer> sj = new ArrayList<>();
        List<String> mz = new ArrayList<>();
        List<User> emp = heTongMapper.tjSyz();
        for (int i=0;i<emp.size();i++){
            sj.add(heTongDao.syzHt(emp.get(i).getEmpId()));
            mz.add(emp.get(i).getEmpName());
        }
        map.put("sj",sj);
        map.put("mz",mz);
        return map;
    }

    @Autowired
    HuiKuanMapper huiKuanMapper;
    //根据订单id找到此订单的所有回款计划
    public List<Huikuan> selectHuiKuanByddId(Integer ddId) {
        return huiKuanMapper.selectHuiKuanByddId(ddId);
    }


    //根据合同id找到合同
    public Hetong selectHeTongByhtIdSh(Integer htId) {
        return heTongMapper.selectHeTongByhtIdSh(htId);
    }

    //根据订单id找到订单
    public Dingdan selectDingDanByddIdSh(Integer ddId) {
        return dingDanMapper.selectDingDanByddIdSh(ddId);
    }

    //退换货：查看所有(执行中)订单
    public List<Dingdan> tuihuanDDzxz(Integer kId) {
        return dingDanMapper.tuihuanDDzxz(kId);
    }



    //{维修工单}根据选择的客户查询客户所有已完成的订单
    public List<Dingdan> wxgdSelectYwcDingDanBykId(Integer kId){
        return dingDanMapper.wxgdSelectYwcDingDanBykId(kId);
    }
}